import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:logging_appenders/logging_appenders.dart';
import 'package:super_tool_server/business/config_manager.dart';
import 'package:intl/intl.dart';

final Logger superLog = Logger('SuperToolServer');

void configLogger() {
  hierarchicalLoggingEnabled = true;

  Logger.root.level = Level.INFO; // 整体开关-下面设置会覆盖这一条

  superLog.level = Level.ALL;
  Directory dir = Directory(ConfigManager.getInstance().getConfigInfo().localLogPath);
  if (dir.existsSync()) {
    final appender = RotatingFileAppender(
        baseFilePath:
            '${ConfigManager.getInstance().getConfigInfo().localLogPath}/${DateFormat('yyyy-MM-dd_HH_mm_ss').format(DateTime.now())}.log',
        keepRotateCount: 10)
      ..attachToLogger(superLog);
  }

  Logger.root.onRecord.listen((LogRecord rec) {
    if (!kReleaseMode) {
      var curMsg = '${rec.loggerName}-${rec.level.name} : ${rec.time}: ${rec.message}';
      print(curMsg);
      if (rec.error != null) {
        print('  ↳  ${rec.error}');
        print(rec.stackTrace.toString());
      }
    }
  });
}
